//
//  AppDelegate.m
//  Car
//
//  Created by lanou on 15/9/17.
//  Copyright (c) 2015年 朱鸿儒. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "GuideView.h"
#import "UMSocial.h"
#import "XGPush.h"

#import "UMSocialQQHandler.h"
#import "UMSocialSinaHandler.h"

#import "UMSocialWechatHandler.h"
#import "UMSocialAccountManager.h"
#import <AVFoundation/AVFoundation.h>


@interface AppDelegate ()<UIScrollViewDelegate>

//  滑动完成判断
@property (nonatomic) BOOL done;

@property (nonatomic, strong) GuideView *guideView;

@property (nonatomic, strong) BaseTabBarController *baseVC;

@end

@implementation AppDelegate



/**
 *  检测当前网络状态
 */
- (NSString *)networkingStatesFromStatebar {
	// 状态栏是由当前app控制的，首先获取当前app
	UIApplication *app = [UIApplication sharedApplication];
	
	NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
	
	int type = 0;
	for (id child in children) {
		if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
			type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
		}
	}
	NSString *stateString = @"wifi";
	
	switch (type) {
		case 0:
			stateString = @"notReachable";
			break;
			
		case 1:
			stateString = @"2G";
			break;
			
		case 2:
			stateString = @"3G";
			break;
			
		case 3:
			stateString = @"4G";
			break;
			
		case 4:
			stateString = @"LTE";
			break;
			
		case 5:
			stateString = @"wifi";
			break;
			
		default:
			break;
	}
	
	return stateString;
}
/**
 *  电台后台播放
 */
- (void)playBackgroud {
	
    AVAudioSession *sesison = [AVAudioSession sharedInstance];
    [sesison setCategory:AVAudioSessionCategoryPlayback error:nil];
    [sesison setActive:YES error:nil];
	
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    self.done = NO;
    
    
    //将角标清零
    [application setApplicationIconBadgeNumber:0];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    //注册信鸽推送服务
    [XGPush startApp:2200152337 appKey:@"I8UJPGG1796I"];
    //如果当前设备为8.0以上.推送服务用以下方式注册
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
        //为我们注册声音.角标.提醒
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
        [application registerUserNotificationSettings:settings];
    }else{
        //8.0以前用以前方法注册
        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
        
    }

    
#pragma mark ---    判断 登录状态 实现自动登录功能
    
    NSUserDefaults *userTM = [NSUserDefaults standardUserDefaults];
    NSArray *arrayTM = [userTM objectForKey:@"tm"];
    
    NSUserDefaults *user911 = [NSUserDefaults standardUserDefaults];
    NSArray *array911 = [user911 objectForKey:@"911"];
    
    if ([arrayTM[0] isEqualToString:array911[0]]) {
        EnterInformationHandle *handle = [EnterInformationHandle share];
        handle.enterOrNot = YES;
		[EnterInformationHandle share].myNumber = arrayTM[0];
    }
    else {
        EnterInformationHandle *handle = [EnterInformationHandle share];
        handle.enterOrNot = NO;
    }

#pragma mark ---   启动时的动画效果
    //  操作沙盒 利用对文件的创建 来判断是否进入过主页
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [path stringByAppendingString:@"/aaa.txt"];
    
    BOOL isHasFile = [manager fileExistsAtPath:file];
    
    if (isHasFile) {
        
        [self gotoMain];
    }
    else {
        
        self.guideView = [[GuideView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
        self.guideView.delegate = self;
        self.guideView.tag = 2001;
        
        UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, kHeight - 100, kWidth, 30)];
        pageControl.currentPage = 0;
        pageControl.numberOfPages = 4;
        pageControl.tag = 1001;
        
        [self.window addSubview:self.guideView];
        [self.window addSubview:pageControl];
//        [manager createFileAtPath:file contents:nil attributes:nil];
        

    
    }

    [SMS_SDK registerApp:@"aa05addeb321" withSecret:@"cfa5290345e07a52f26441af4237b4c2"];
    [self.window makeKeyAndVisible];
    [self playBackgroud];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    //非原生
    [UMSocialData setAppKey:@"5606df08e0f55a58d1003b4b"];
//    [UMSocialSinaHandler openSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    //打开新浪微博的SSO开关，设置新浪微博回调地址，这里必须要和你在新浪微博后台设置的回调地址一致。若在新浪后台设置我们的回调地址，“http://sns.whalecloud.com/sina2/callback”，这里可以传nil
    
    /**
     *  设置微信分享
     */
	   [UMSocialWechatHandler setWXAppId:@"wxfc63d3f06e2236a2" appSecret:@"05c26ae93235b9b46f084cf923be05fd" url:@"http://www.umeng.com/social"];
    /**
     *  设置QQ和空间分享
     */
    [UMSocialQQHandler setQQWithAppId:@"1104815781" appKey:@"n3jxerdugz2LAOI6" url:@"http://www.umeng.com/social"];
	
	NSString *netStatus = [self networkingStatesFromStatebar];
	NSLog(@"%@", netStatus);
    [self.window addSubview:navigationController.view];
    
    return YES;
}



- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [XGPush registerDevice:deviceToken];
    NSLog(@"%@", [XGPush registerDevice:deviceToken]);
    NSLog(@"%@", deviceToken);
    
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    [application registerForRemoteNotifications];
}



- (void)gotoMain {
    
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [path stringByAppendingString:@"/aaa.txt"];
    NSLog(@"%@",file);
    
    if (![manager fileExistsAtPath:file]) {
        [manager createFileAtPath:file contents:nil attributes:nil];
    }
    
    
    self.baseVC = [[BaseTabBarController alloc]init];
    self.baseVC.tabBar.translucent = NO;
    self.window.rootViewController = self.baseVC;

}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    // 滚动判断
    if (self.guideView.contentOffset.x >= kWidth * 3) {
        
        self.done = YES;

    }

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView.tag == 2001) {
        
        UIPageControl *page = (UIPageControl *)[self.window viewWithTag:1001];
        page.currentPage = scrollView.contentOffset.x / kWidth;
    }
    
    
    
    if (self.done) {
        [UIView animateWithDuration:1.5 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            //  动画效果 逐渐消失 使透明度变成0
            self.guideView.alpha = 0;
        } completion:^(BOOL finished) {
            [self.guideView removeFromSuperview];
            
            [self gotoMain];
        }];
        
    }
    
    
    
}



- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication

         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
   
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou3g.Car" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Car" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Car.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
